<script setup>
import MetaCode from "@/components/MetaCode.vue"
import Meta3Part from "@/components/Meta3Part.vue"
import MetaIcon from "@/components/MetaIcon.vue"
import {render, state, execute} from '@/utils/tmpl.js'
import {useDark, useToggle} from "@vueuse/core";

// 样例、模板、渲染结果选项
const result = computed(() => {
  try {
    const jsonData = JSON.parse(state.json)
    if (state.module === 'JavaScript引擎') {
      const tmplData = state.jsTmpl
      return execute(jsonData, tmplData)
    } else {
      const tmplData = state.tmpl[state.lang]
      return render('art', tmplData, jsonData).trim()
    }
  } catch (e) {
    return `json数据解析错误，${e}`
  }
})

// 是否是js引擎功能
const isJsEngine = computed(() => state.module === 'JavaScript引擎')
// 主题切换
const isDark = useDark()
const toggleDark = useToggle(isDark)
</script>

<template>
  <meta3-part style="height: 100vh; overflow: hidden">
    <template v-slot:header>
      <MetaCode v-model:value="state.json" language="json"/>
      <div class="hint">
        <el-button type="primary">json数据</el-button>
      </div>
    </template>

    <template v-slot:main>
      <MetaCode v-if="isJsEngine" v-model:value="state.jsTmpl" language="javascript"/>
      <MetaCode v-else v-model:value="state.tmpl[state.lang]" :language="state.lang"/>
      <div class="hint" style="bottom: 5px">
        <el-segmented v-model="state.module" :options="state.modules" />
      </div>
      <div class="lang" v-if="!isJsEngine">
        <!-- 功能选择 -->
        <div>
          <el-select v-model="state.lang" style="width: 100px">
            <el-option v-for="(_, key) in state.tmpl" :value="key" :label="key" :key="key">
              <MetaIcon :name="key" :icon="key"/>
            </el-option>
            <template #label="{ value }">
              <MetaIcon :name="value" :icon="value"/>
            </template>
          </el-select>
        </div>
      </div>
    </template>

    <template v-slot:right>
      <MetaCode :value="result" :readOnly="true" :language="isJsEngine ? 'javascript' : state.lang"/>
      <div class="hint">
        <el-button type="primary">结果区域</el-button>
      </div>
      <div class="theme">
        <MetaIcon name="切换主题" icon="theme" tooltip
                  @click="toggleDark()"
                  style="cursor: pointer"/>
      </div>
    </template>
  </meta3-part>
</template>

<style scoped lang="scss">
.hint {
  position: absolute;
  bottom: 10px;
  right: 10px;
}

.lang {
  position: absolute;
  top: 10px;
  right: 10px;
}

.theme {
  position: absolute;
  bottom: 10px;
  left: 10px;
}
.codemirror-opacity {
  opacity: 0.8;
}
</style>